package com.wits.qso.service;

import java.text.NumberFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authc.credential.PasswordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wits.platform.common.constants.UserType;
import com.wits.platform.dao.MmrUserRoleDao;
import com.wits.platform.entity.MmrUserRole;
import com.wits.platform.entity.User;
import com.wits.platform.service.BaseService;
import com.wits.platform.service.UserService;
import com.wits.qso.dao.StudentDao;
import com.wits.qso.entity.Student;

@Component
public class StudentService extends BaseService<Student, String>
{
	protected static final Logger logger = LoggerFactory.getLogger( StudentService.class );
	private StudentDao stuDao;

	@Autowired
	private UserService userService = null;
	@Autowired
	private PasswordService passwordService = null;
	@Resource
	private MmrUserRoleDao mmrUserRoleDao;

	@Autowired
	public void setStuDao(StudentDao stuDao) {
		this.baseDao = stuDao;
		this.stuDao = stuDao;
	}

	public User getUser(String stuUserId) {
		List<User> list = stuDao.getUser( stuUserId );
		if (list.size() > 0)
			return list.get( 0 );
		return null;
	}

	/**
	 * @see 根据userId查询
	 * @param userId
	 * @return
	 */
	public Student findByUserId(final String userId) {
		List<Student> list = stuDao.findAll( new Specification<Student>() {
			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				return cb.equal( root.get( "stuUserId" ), userId );
			}
		} );
		return list.size() > 0 ? list.get( 0 ) : null;
	}

	public List<Student> findByDiscussionGroupId(String groupId) {
		return stuDao.findByDiscussionGroupId( groupId );
	}

	public List<Student> findByClsId(String clsId) {
		// TODO Auto-generated method stub
		return stuDao.findByClsId( clsId );
	}

	/**
	 * 查询学生的用户id
	 * 
	 * @param clsId
	 *            班级id
	 * @return
	 */
	public List<String> findUserIdByClsId(String clsId) {
		// TODO Auto-generated method stub
		return stuDao.findUserIdByClsId( clsId );
	}

	public void insertUserRole(MmrUserRole model) {
		mmrUserRoleDao.save( model );
	}

	public int batchStudentData(Workbook workbook, String currentUserId) {
		int result = 0;
		Sheet sheet = workbook.getSheetAt( 0 );
		try {
			for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
				Row row = sheet.getRow( i );
				Student student = new Student();
				student.setStuName( (String) getCellValue( row.getCell( 0 ) ) );
				student.setStuSex( (String) getCellValue( row.getCell( 1 ) ) );
				student.setStuTel( (String) getCellValue( row.getCell( 2 ) ) );
				student.setStuMail( (String) getCellValue( row.getCell( 3 ) ) );
				student.setStuUserId( (String) getCellValue( row.getCell( 4 ) ) );
				student.setClsId( (String) getCellValue( row.getCell( 5 ) ) );
				student.setDateExpire( (Date) getCellValue( row.getCell( 6 ) ) );
				student.setRemark( (String) getCellValue( row.getCell( 7 ) ) );
				student.setDateCre( new Date() );
				student.setUserCre( currentUserId );

				User user = new User();
				user.setUserId( student.getStuUserId() );
				user.setUserNameC( student.getStuName() );
				user.setDateExpire( student.getDateExpire() );
				user.setIsEnable( "T" );
				user.setUsertype( UserType.STUDENT.getValue() );
				user.setUserPassword( passwordService.encryptPassword( "123456" ) );
				user.setUserCre( currentUserId );
				user.setUserEmail( student.getStuMail() );
				user.setDateCre( new Date() );

				if (!userService.isExist( user )) {
					this.save( student );
					userService.saveCascade( user ); // 保存到wits_user表

					result++;
				}
			}
		} catch (Throwable cause) {
			logger.error( cause.getMessage(), cause );
		}

		return result;
	}

	private Object getCellValue(Cell cell) {
		Object result = null;
		if (null != cell) {
			switch (cell.getCellType()) {
				case Cell.CELL_TYPE_STRING:
					result = cell.getRichStringCellValue().getString();
					break;
				case Cell.CELL_TYPE_NUMERIC:
					if (DateUtil.isCellDateFormatted( cell )) {
						result = cell.getDateCellValue();
					} else {
						NumberFormat nf = NumberFormat.getInstance();
						nf.setGroupingUsed( false );
						result = String.valueOf( nf.format( cell.getNumericCellValue() ) );
					}
					break;
			}
		}

		return result;
	}
}
